package com.heima.article.controller;

import com.heima.article.entity.ApArticle;
import com.heima.article.es.ApArticleSearch;
import com.heima.article.es.ApArticleSearchRepository;
import com.heima.article.service.IApArticleService;
import com.heima.common.dto.ResponseResult;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.elasticsearch.core.ElasticsearchRestTemplate;
import org.springframework.data.elasticsearch.core.query.IndexQuery;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.List;

@RestController
@RequestMapping("/test")
public class TestController {

    @Autowired
    private ElasticsearchRestTemplate restTemplate;

    @Autowired
    private IApArticleService articleService;

    @Autowired
    private ApArticleSearchRepository articleSearchRepository;

    // 创建es索引
    @GetMapping("/index")
    public ResponseResult createIndex() {
        restTemplate.createIndex(ApArticleSearch.class);
        return ResponseResult.okResult();
    }

    // 添加映射关系
    @GetMapping("/mapping")
    public ResponseResult putMapping() {
        restTemplate.putMapping(ApArticleSearch.class);
        return ResponseResult.okResult();
    }

    // 从数据库读文章数据同步到es中
    @GetMapping("/update")
    public ResponseResult update() {
        List<ApArticle> articles = articleService.list();
        List<ApArticleSearch> list = new ArrayList<>();
        for (ApArticle article : articles) {
            ApArticleSearch search = new ApArticleSearch();
            BeanUtils.copyProperties(article, search);
            list.add(search);
        }
        // 保存到es
        List<IndexQuery> indexQuery = new ArrayList<>();
        for (ApArticleSearch articleSearch : list) {
            IndexQuery query = new IndexQuery();
            query.setId(articleSearch.getId().toString());
            query.setObject(articleSearch);
            indexQuery.add(query);
        }
        restTemplate.bulkIndex(indexQuery);
        return ResponseResult.okResult();
    }


    // 从数据库读文章数据同步到es中
    @GetMapping("/save")
    public ResponseResult save() {
        // 先删除所有记录
        articleSearchRepository.deleteAll();

        List<ApArticle> articles = articleService.list();
        List<ApArticleSearch> list = new ArrayList<>();
        for (ApArticle article : articles) {
            ApArticleSearch search = new ApArticleSearch();
            BeanUtils.copyProperties(article, search);
            list.add(search);
        }
        // 保存到es
        articleSearchRepository.saveAll(list);
        return ResponseResult.okResult();
    }
}
